using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using community.Data;

namespace community.Controllers
{
    /// <summary>
    /// 社区活动查询参数
    /// </summary>
    public class EventQueryDTO
    {
        /// <summary>
        /// 活动标题
        /// </summary>
        public string? Title { get; set; }

        /// <summary>
        /// 活动地点
        /// </summary>
        public string? Location { get; set; }

        /// <summary>
        /// 开始时间起始点
        /// </summary>
        public DateTime? StartTimeFrom { get; set; }

        /// <summary>
        /// 开始时间结束点
        /// </summary>
        public DateTime? StartTimeTo { get; set; }

        /// <summary>
        /// 是否仅显示可报名活动（未结束且未满员）
        /// </summary>
        public bool? OnlyAvailable { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新社区活动的数据模型
    /// </summary>
    public class CommunityEventDTO
    {
        /// <summary>
        /// 活动标题
        /// </summary>
        [Required(ErrorMessage = "活动标题不能为空")]
        [StringLength(200, ErrorMessage = "活动标题最多200个字符")]
        public string Title { get; set; }

        /// <summary>
        /// 活动描述
        /// </summary>
        [Required(ErrorMessage = "活动描述不能为空")]
        public string Description { get; set; }

        /// <summary>
        /// 活动开始时间
        /// </summary>
        [Required(ErrorMessage = "开始时间不能为空")]
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 活动结束时间
        /// </summary>
        [Required(ErrorMessage = "结束时间不能为空")]
        public DateTime EndTime { get; set; }

        /// <summary>
        /// 活动地点
        /// </summary>
        [Required(ErrorMessage = "活动地点不能为空")]
        [StringLength(200, ErrorMessage = "活动地点最多200个字符")]
        public string Location { get; set; }

        /// <summary>
        /// 最大参与人数
        /// </summary>
        [Required(ErrorMessage = "最大参与人数不能为空")]
        [Range(1, 1000, ErrorMessage = "最大参与人数必须在1-1000之间")]
        public int MaxParticipants { get; set; }
    }

    /// <summary>
    /// 社区活动管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CommunityEventController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public CommunityEventController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取社区活动列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>活动列表和总数</returns>
        /// <response code="200">成功获取活动列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetEvents([FromQuery] EventQueryDTO query)
        {
            var events = _context.CommunityEvents.AsQueryable();

            if (!string.IsNullOrEmpty(query.Title))
                events = events.Where(e => e.Title.Contains(query.Title));

            if (!string.IsNullOrEmpty(query.Location))
                events = events.Where(e => e.Location.Contains(query.Location));

            if (query.StartTimeFrom.HasValue)
                events = events.Where(e => e.StartTime >= query.StartTimeFrom);

            if (query.StartTimeTo.HasValue)
                events = events.Where(e => e.StartTime <= query.StartTimeTo);

            if (query.OnlyAvailable == true)
            {
                var now = DateTime.UtcNow;
                events = events.Where(e => e.EndTime > now);
            }

            var total = await events.CountAsync();

            var pagedEvents = await events
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .ToListAsync();

            // 获取每个活动的当前报名人数
            var eventIds = pagedEvents.Select(e => e.Id).ToList();
            var registrationCounts = new Dictionary<int, int>();
            
            foreach (var eventId in eventIds)
            {
                var count = await _context.EventRegistrations
                    .CountAsync(r => r.EventId == eventId);
                registrationCounts[eventId] = count;
            }

            var result = pagedEvents.Select(e => new
            {
                e.Id,
                e.Title,
                e.Description,
                e.StartTime,
                e.EndTime,
                e.Location,
                e.MaxParticipants,
                CurrentParticipants = registrationCounts.GetValueOrDefault(e.Id, 0),
                IsAvailable = e.EndTime > DateTime.UtcNow && 
                    registrationCounts.GetValueOrDefault(e.Id, 0) < e.MaxParticipants
            });

            return Ok(new
            {
                Total = total,
                Items = result
            });
        }

        /// <summary>
        /// 获取指定活动的详细信息
        /// </summary>
        /// <param name="id">活动ID</param>
        /// <returns>活动详细信息</returns>
        /// <response code="200">成功获取活动信息</response>
        /// <response code="404">指定ID的活动不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetEvent(int id)
        {
            var communityEvent = await _context.CommunityEvents
                .Include(e => e.Registrations)
                    .ThenInclude(r => r.User)
                .FirstOrDefaultAsync(e => e.Id == id);

            if (communityEvent == null)
                return NotFound();

            var registrationCount = communityEvent.Registrations.Count;

            return Ok(new
            {
                communityEvent.Id,
                communityEvent.Title,
                communityEvent.Description,
                communityEvent.StartTime,
                communityEvent.EndTime,
                communityEvent.Location,
                communityEvent.MaxParticipants,
                CurrentParticipants = registrationCount,
                IsAvailable = communityEvent.EndTime > DateTime.UtcNow && 
                    registrationCount < communityEvent.MaxParticipants,
                Registrations = communityEvent.Registrations.Select(r => new
                {
                    r.User.Username,
                    r.User.Email,
                    r.RegisteredAt
                })
            });
        }

        /// <summary>
        /// 创建新活动
        /// </summary>
        /// <param name="dto">活动信息</param>
        /// <returns>新创建的活动信息</returns>
        /// <response code="201">成功创建活动</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreateEvent(CommunityEventDTO dto)
        {
            if (dto.EndTime <= dto.StartTime)
                return BadRequest("结束时间必须晚于开始时间");

            var communityEvent = new CommunityEvent
            {
                Title = dto.Title,
                Description = dto.Description,
                StartTime = dto.StartTime,
                EndTime = dto.EndTime,
                Location = dto.Location,
                MaxParticipants = dto.MaxParticipants,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            _context.CommunityEvents.Add(communityEvent);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetEvent), new { id = communityEvent.Id }, communityEvent);
        }

        /// <summary>
        /// 更新活动信息
        /// </summary>
        /// <param name="id">活动ID</param>
        /// <param name="dto">更新的活动信息</param>
        /// <returns>更新后的活动信息</returns>
        /// <response code="200">成功更新活动信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的活动不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateEvent(int id, CommunityEventDTO dto)
        {
            var communityEvent = await _context.CommunityEvents.FindAsync(id);
            if (communityEvent == null)
                return NotFound();

            if (dto.EndTime <= dto.StartTime)
                return BadRequest("结束时间必须晚于开始时间");

            communityEvent.Title = dto.Title;
            communityEvent.Description = dto.Description;
            communityEvent.StartTime = dto.StartTime;
            communityEvent.EndTime = dto.EndTime;
            communityEvent.Location = dto.Location;
            communityEvent.MaxParticipants = dto.MaxParticipants;
            communityEvent.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(communityEvent);
        }

        /// <summary>
        /// 删除活动
        /// </summary>
        /// <param name="id">活动ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除活动</response>
        /// <response code="404">指定ID的活动不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteEvent(int id)
        {
            var communityEvent = await _context.CommunityEvents.FindAsync(id);
            if (communityEvent == null)
                return NotFound();

            _context.CommunityEvents.Remove(communityEvent);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        /// <summary>
        /// 报名参加活动
        /// </summary>
        /// <param name="id">活动ID</param>
        /// <returns>报名结果</returns>
        /// <response code="200">成功报名</response>
        /// <response code="400">活动已结束或已满员</response>
        /// <response code="404">指定ID的活动不存在</response>
        [HttpPost("{id}/register")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> RegisterEvent(int id)
        {
            var communityEvent = await _context.CommunityEvents.FindAsync(id);
            if (communityEvent == null)
                return NotFound();

            if (communityEvent.EndTime <= DateTime.UtcNow)
                return BadRequest("活动已结束");

            var currentParticipants = await _context.EventRegistrations
                .CountAsync(r => r.EventId == id);

            if (currentParticipants >= communityEvent.MaxParticipants)
                return BadRequest("活动已满员");

            // TODO: 获取当前用户ID（需要认证系统支持）
            var userId = 1; // 临时使用固定值

            // 检查是否重复报名
            var exists = await _context.EventRegistrations
                .AnyAsync(r => r.EventId == id && r.UserId == userId);

            if (exists)
                return BadRequest("您已报名此活动");

            var registration = new EventRegistration
            {
                EventId = id,
                UserId = userId,
                RegisteredAt = DateTime.UtcNow
            };

            _context.EventRegistrations.Add(registration);
            await _context.SaveChangesAsync();

            return Ok(new { Message = "报名成功" });
        }

        /// <summary>
        /// 取消活动报名
        /// </summary>
        /// <param name="id">活动ID</param>
        /// <returns>取消结果</returns>
        /// <response code="200">成功取消报名</response>
        /// <response code="400">未找到报名记录</response>
        /// <response code="404">指定ID的活动不存在</response>
        [HttpDelete("{id}/register")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> CancelRegistration(int id)
        {
            var communityEvent = await _context.CommunityEvents.FindAsync(id);
            if (communityEvent == null)
                return NotFound();

            // TODO: 获取当前用户ID（需要认证系统支持）
            var userId = 1; // 临时使用固定值

            var registration = await _context.EventRegistrations
                .FirstOrDefaultAsync(r => r.EventId == id && r.UserId == userId);

            if (registration == null)
                return BadRequest("未找到报名记录");

            _context.EventRegistrations.Remove(registration);
            await _context.SaveChangesAsync();

            return Ok(new { Message = "已取消报名" });
        }
    }
} 